<template>
	<view class="uni-container">
		<!-- 操作工具栏 -->
		<view class="uni-toolbar">
			<button class="uni-button primary" @tap="showAddDialog">
				<text class="iconfont icon-add"></text> 新增
			</button>
			<button class="uni-button default" @tap="handleExport">
				<text class="iconfont icon-export"></text> 导出
			</button>
		</view>

		<!-- 筛选表单 -->
		<view class="uni-filter-box">
			<view class="uni-filter-item" v-for="(item, index) in filterFields" :key="index">
				<text class="uni-filter-label">{{ item.label }}</text>
				<input class="uni-input" v-model="formData[item.prop]" :placeholder="item.placeholder" />
			</view>
			<button class="uni-button search" @tap="submitForm">
				<text class="iconfont icon-search"></text> 搜索
			</button>
		</view>

		<!-- 合同数据表格 -->
		<uni-table ref="table" border stripe type="selection" :data="tableData" empty-text="暂无数据"
			@selection-change="handleSelectionChange">
			<uni-tr>
				<uni-th width="100" align="center" v-for="(col, idx) in tableColumns" :key="idx">
					{{ col.label }}
				</uni-th>
				<uni-th width="150" align="center">操作</uni-th>
			</uni-tr>

			<uni-tr v-for="(item, index) in tableData" :key="index">
				<uni-td align="center" v-for="(col, colIdx) in tableColumns" :key="colIdx">
					{{ col.formatter ? col.formatter(item[col.prop]) : item[col.prop] }}
				</uni-td>
				<uni-td align="center">
					<view class="uni-group">
						<button class="uni-button mini primary" @tap="editRow(item)">修改</button>
						<button class="uni-button mini danger" @tap="deleteRow(item)">删除</button>
					</view>
				</uni-td>
			</uni-tr>
		</uni-table>

		<!-- 分页组件 -->
		<view class="uni-pagination-box">
			<uni-pagination show-icon :page-size="formData.pageSize" :current="formData.pageNum" :total="total"
				@change="handlePaginationChange" />
		</view>

	</view>
</template>
<script>
	import {
		add,
		list,
		update
	} from "@/api/registration";

	export default {
		data() {
			return {
				// 定义筛选字段  
				filterFields: [{
						prop: 'clientName',
						label: '客户名称',
						placeholder: '请输入客户名称'
					},
					{
						prop: 'contractType',
						label: '合同类别',
						placeholder: '请输入合同类别'
					},
					{
						prop: 'businessManager',
						label: '业务经理',
						placeholder: '请输入业务经理'
					},
					{
						prop: 'PaymentCollectionYear',
						label: '回款年度',
						placeholder: '请输入回款年度'
					}
				],
				 tableColumns: [  
				      { prop: 'contractNumber', label: '合同编号' },  
				      { prop: 'contractType', label: '合同类别' },  
				      { prop: 'clientName', label: '客户名称' },  
				      { prop: 'paymentYear', label: '回款年度' },  
				      { prop: 'businessManager', label: '业务经理' },  
				      { prop: 'contractAmount', label: '合同金额' },  
				      { prop: 'receivableAmount', label: '应收金额' },  
				      { prop: 'actualAmount', label: '实收金额' },  
				      { prop: 'unreturnedAmount', label: '未回金额' },  
				      { prop: 'startDate', label: '起始日期', formatter: this.formatDate },  
				      { prop: 'endDate', label: '终止日期', formatter: this.formatDate }  
				    ] ,
				// 查询参数  
				formData: {
					pageNum: 1,
					pageSize: 10,
					clientName: '',
					contractType: undefined,
					businessManager: '',
					PaymentCollectionYear: '',
				},
				total: 0,
				tableData: [],
				selectedRows: [],
				newContractForm: {
					contractNumber: '',
					contractType: '',
					clientName: '',
					paymentYear: '',
					businessManager: '',
					contractAmount: '',
					receivableAmount: '',
					actualAmount: '',
					unreturnedAmount: '',
					startDate: '',
					endDate: ''
				},
				editContractForm: {
					contractNumber: '',
					contractType: '',
					clientName: '',
					paymentYear: '',
					businessManager: '',
					contractAmount: '',
					receivableAmount: '',
					actualAmount: '',
					unreturnedAmount: '',
					startDate: '',
					endDate: ''
				}
			}
		},
		created() {
			this.getList();
		},
		methods: {
			// 导出功能  
			async handleExport() {
				try {
					const res = await uni.downloadFile({
						url: '/client/registration/export',
						data: this.formData,
						header: {
							'Content-Type': 'application/json'
						}
					});

					if (res.statusCode === 200) {
						uni.saveFile({
							tempFilePath: res.tempFilePath,
							fileName: `registration_${new Date().getTime()}.xlsx`
						});
					}
				} catch (e) {
					uni.showToast({
						title: '导出失败',
						icon: 'none'
					});
				}
			},

			// 提交编辑表单  
			async submitEditContract() {
				if (!this.validateForm(this.editContractForm)) return;

				try {
					const res = await update(this.editContractForm);
					if (res.msg === '操作成功') {
						uni.showToast({
							title: '修改成功',
							icon: 'success'
						});
						this.getList();
						this.$refs.editDialog.close();
						this.resetEditForm();
					}
				} catch (e) {
					console.error(e);
				}
			},

			// 表单重置  
			resetForm(type) {
				if (type === 'add') {
					this.newContractForm = {
						contractNumber: '',
						contractType: '',
						clientName: '',
						paymentYear: '',
						businessManager: '',
						contractAmount: '',
						receivableAmount: '',
						actualAmount: '',
						unreturnedAmount: '',
						startDate: '',
						endDate: ''
					};
				} else {
					this.editContractForm = {
						...this.newContractForm
					};
				}
			},

			// 搜索提交  
			submitForm() {
				this.formData.pageNum = 1;
				this.getList();
			},

			// 获取数据列表  
			async getList() {
				try {
					const res = await list(this.formData);
					this.tableData = res.rows.map(item => ({
						...item,
						startDate: this.formatDate(item.startDate),
						endDate: this.formatDate(item.endDate)
					}));
					this.total = res.total;
					console.log(res);
				} catch (e) {
					console.error(e);
				}
			},

			// 显示新增弹窗  
			showAddDialog() {
				this.$refs.addDialog.open();
			},

			// 提交新合同  
			async submitNewContract() {
				if (!this.validateForm(this.newContractForm)) return;

				try {
					const res = await add(this.newContractForm);
					if (res.msg === '操作成功') {
						uni.showToast({
							title: '新增成功',
							icon: 'success'
						});
						this.getList();
						this.$refs.addDialog.close();
						this.resetForm('add');
					}
				} catch (e) {
					console.error(e);
				}
			},

			// 编辑行数据  
			editRow(row) {
				this.editContractForm = {
					...row
				};
				this.$refs.editDialog.open();
			},

			// 删除行数据  
			async deleteRow(row) {
				uni.showModal({
					title: '警告',
					content: `确定删除 ${row.contractNumber} 吗?`,
					success: async (res) => {
						if (res.confirm) {
							try {
								await update({
									id: row.id,
									isDeleted: '1'
								});
								this.tableData = this.tableData.filter(item => item !== row);
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
							} catch (e) {
								console.error(e);
							}
						}
					}
				});
			},

			// 表单验证  
			validateForm(form) {
				const requiredFields = [
					'contractNumber',
					'clientName',
					'contractAmount'
				];

				return requiredFields.every(field => {
					if (!form[field]) {
						uni.showToast({
							title: `请输入${this.getFieldName(field)}`,
							icon: 'none'
						});
						return false;
					}
					return true;
				});
			},

			// 获取字段中文名  
			getFieldName(field) {
				const map = {
					contractNumber: '合同编号',
					clientName: '客户名称',
					contractAmount: '合同金额'
				};
				return map[field] || '';
			},

			// 日期格式化  
			formatDate(timestamp) {
				if (!timestamp) return '';
				const date = new Date(timestamp);
				return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')}`;
			},

			// 分页变化  
			handlePaginationChange(e) {
				this.formData.pageNum = e.current;
				this.getList();
			},

			// 多选处理  
			handleSelectionChange(e) {
				this.selectedRows = e.detail.index;
			}
		}
	}
</script>
<style scoped>  
/* 页面容器 */  
.uni-container {  
  padding: 20rpx;  
  background: #f9f9f9;  
  min-height: 100vh;  
  box-sizing: border-box;  
}  

/* 操作工具栏 */  
.uni-toolbar {  
  display: flex;  
  gap: 20rpx;  
  margin-bottom: 20rpx;  
}  

.uni-button {  
  flex: 1;  
  height: 64rpx;  
  line-height: 64rpx;  
  font-size: 28rpx;  
  text-align: center;  
  border-radius: 8rpx;  
  transition: background-color 0.3s ease;  
}  

.uni-button.primary {  
  background-color: #409eff;  
  color: #fff;  
  border: none;  
}  

.uni-button.default {  
  background-color: #ffffff;  
  color: #333;  
  border: 1rpx solid #ddd;  
}  

.uni-button.danger {  
  background-color: #f56c6c;  
  color: #fff;  
}  

.uni-button.search {  
  background-color: #00c46c;  
  color: #fff;  
}  

/* 筛选表单 */  
.uni-filter-box {  
  display: flex;  
  flex-wrap: wrap;  
  gap: 20rpx;  
  margin-bottom: 20rpx;  
  background: #fff;  
  padding: 20rpx;  
  border-radius: 8rpx;  
  box-shadow: 0 5rpx 10rpx rgba(0, 0, 0, 0.1);  
}  

.uni-filter-item {  
  flex: 1;  
  min-width: 200rpx;  
}  

.uni-filter-label {  
  font-size: 26rpx;  
  color: #606266;  
  margin-bottom: 12rpx;  
}  

.uni-input {  
  height: 60rpx;  
  padding: 0 16rpx;  
  line-height: 60rpx;  
  border: 1rpx solid #dcdfe6;  
  border-radius: 4rpx;  
  font-size: 28rpx;  
  color: #606266;  
  box-sizing: border-box;  
}  

/* 表格区域 */  
.uni-table {  
  margin-top: 20rpx;  
  background: #fff;  
  border-radius: 8rpx;  
  box-shadow: 0 5rpx 10rpx rgba(0, 0, 0, 0.1);  
}  

/* 分页组件 */  
.uni-pagination-box {  
  margin-top: 20rpx;  
  text-align: center;  
}  

/* 弹窗样式 */  
.dialog-container {  
  background: #ffffff;  
  padding: 30rpx;  
  border-radius: 16rpx;  
  width: 86%;  
  max-height: 80vh;  
  overflow-y: auto;  
  box-sizing: border-box;  
}  

.dialog-title {  
  font-size: 36rpx;  
  color: #333333;  
  font-weight: bold;  
  margin-bottom: 20rpx;  
  text-align: center;  
}  

/* 表单内容 */  
.form-body {  
  display: flex;  
  flex-wrap: wrap;  
  gap: 20rpx;  
}  

.form-row {  
  width: 48%;  
  margin-bottom: 20rpx;  
}  

.form-label {  
  font-size: 28rpx;  
  color: #606266;  
  margin-bottom: 8rpx;  
}  

.form-input {  
  height: 60rpx;  
  padding: 0 20rpx;  
  border: 1rpx solid #dcdfe6;  
  border-radius: 8rpx;  
  font-size: 28rpx;  
  box-sizing: border-box;  
}  

/* 弹窗底部按钮 */  
.dialog-footer {  
  margin-top: 20rpx;  
  display: flex;  
  justify-content: space-between;  
  gap: 20rpx;  
}  

.dialog-footer .uni-button {  
  flex: 1;  
  height: 60rpx;  
  line-height: 60rpx;  
  font-size: 28rpx;  
  text-align: center;  
  border-radius: 8rpx;  
  transition: background-color 0.3s ease;  
}  

.dialog-footer .uni-button.cancel {  
  background-color: #e5e5e5;  
  color: #333333;  
}  

.dialog-footer .uni-button.confirm {  
  background-color: #409eff;  
  color: #ffffff;  
}  

/* 响应式适配 */  
@media (max-width: 750rpx) {  
  .uni-filter-item {  
    flex: 1 1 100%;  
  }  

  .form-row {  
    width: 100%;  
  }  
}  
</style>